package com.lxd.sunso.product.netty.server.websocket;

import com.lxd.sunso.product.components.ConversionUtil;
import com.lxd.sunso.product.netty.domain.Device;
import com.lxd.sunso.product.netty.server.socket.NettyServerHandler;
import com.lxd.sunso.product.netty.util.CacheUtil;
import com.lxd.sunso.product.service.NettyService;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import java.util.Collection;


/**
 * TextWebSocketFrame表示一个文本帧
 */
public class MyTextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private Logger logger = LoggerFactory.getLogger(MyTextWebSocketFrameHandler.class);

    @Autowired
    private NettyService nettyService;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //logger.info("链接报告完毕");
        CacheUtil.wsChannelGroup.add(ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        if (CacheUtil.binFile.size() == 0) {
            return;
        }
        //获取设备的名称

        String machineName = msg.text();
        System.out.println(machineName);
        Collection<Device> deviceInfos = CacheUtil.deviceGroup.values();
        Device deviceEntity = null;
        for (Device device : deviceInfos) {
            if (device.getMachineName().equals(machineName)) {
                deviceEntity = device;
                Channel channel = CacheUtil.cacheClientChannel.get(device.getChannelId());
                String message = "5b000000fd0200fff05d";
                byte[] bytes = ConversionUtil.hexStringToByteArray(message);
                channel.writeAndFlush(Unpooled.copiedBuffer(bytes));
            }
        }
    }

    //当web客户端连接后，就会触发这个请求
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();//关闭连接
        CacheUtil.wsChannelGroup.remove(ctx.channel());
    }
}
